var page=0;
var sum=0;
var currentPageIndex;// 当前页码数
var currentCount;// 当前总数
var thisUserId;//当前打开的userId
layui.use(['form','layer','laydate','table','laytpl'],function(){
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laydate = layui.laydate,
        laytpl = layui.laytpl,
        table = layui.table;


	//直播间用户列表
	var tableInsLiveRoom = table.render({
		elem: '#liveRoomByUser_table'
		,url:request("/console/find/liveroom")
		,toolbar: '#toolbar'
		,id: 'liveRoomByUser_table'
		,page: true
		,curr: 0
		,limit:Common.limit
		,limits:Common.limits
		,groups: 7
		,cols: [[ //表头
			{field: '_id', title: '创建者Id', width:'12%'}
			,{field: 'nickname', title: '昵称', width:'12%'}
			,{field: 'liveCount', title: '直播间数量', width:'12%'}
			,{fixed: 'right',title:"操作",width:'20%', align:'left', toolbar: '#liveRoomByUserBar'}
		]]
		,done:function(res, curr, count){
			checkRequst(res);
			//权限判断
			var arr=['liveRoom-lock','liveRoom-chatMessage','liveRoom-member','liveRoom-add'];
			manage.authButton(arr);

			//获取当前每页大小
			var recodeLimit =  $(".layui-laypage-limits").find("option:selected").val();
			if (undefined != recodeLimit){
				//获取零时保留的值
				var last_value = $("#liveRoom_limlt").val();
				//设置零时保留的值
				$("#liveRoom_limlt").val(recodeLimit);
				//判断是否改变了每页大小数
				if (last_value != recodeLimit){
					// 刷新
					table.reload("liveRoom_table",{
						url:request("/console/liveRoomList"),
						page: {
							curr: 1 //重新从第 1 页开始
						}
					})
				}
			}
			var pageIndex = tableInsLiveRoom.config.page.curr;//获取当前页码
			var resCount = res.count;// 获取table总条数
			currentCount = resCount;
			currentPageIndex = pageIndex;
		}
	});

	table.on('tool(liveRoomByUser_table)', function(obj){
		var layEvent = obj.event,
			data = obj.data;
		if(layEvent === 'disable'){ //锁定直播间
			Live.deleteLiveRoom(data.userId,1);
		}else if(layEvent === 'relieveDisable'){// 解锁的直播间
			Live.deleteLiveRoom(data.userId,0);
		}else if(layEvent === 'lookUserLive'){
			thisUserId = data._id;
			//直播间列表
			var tableInsLiveRoom = table.render({
			  elem: '#liveRoom_table'
			  ,url:request("/console/liveRoomList")+"&userId="+data._id
			  ,toolbar: '#toolbar'
			  ,id: 'liveRoom_table'
			  ,page: true
			  ,curr: 0
			  ,limit:Common.limit
			  ,limits:Common.limits
			  ,groups: 7
			  ,cols: [[ //表头
				   {field: 'name', title: '直播间名称',width:'10%'}
				  ,{field: 'notice', title: '房间公告',width:'10%'}
				  ,{field: 'userId', title: '创建者Id', width:'10%'}
				  ,{field: 'nickName', title: '创建者昵称', width:'15%'}
				  ,{field: 'url', title: '推流地址', width:'15%'}
				  ,{field: 'currentState', title: '直播间当前状态', width:150,templet : function (d) {
							if(d.currentState == 0)
								return "正常";
							else if(d.currentState == 1)
								return "被封锁";
						}}
				  ,{field: 'createTime',title:'创建时间',width:'15%',templet: function(d){
						return UI.getLocalTime(d.createTime);
				  }}
				  ,{fixed: 'right',title:"操作",width:'23%', align:'left', toolbar: '#liveRoomListBar'}
				]]
				,done:function(res, curr, count){
					checkRequst(res);
					//权限判断
					var arr=['liveRoom-lock','liveRoom-chatMessage','liveRoom-member','liveRoom-add'];
					manage.authButton(arr);

					//获取零时保留的值
					var last_value = $("#liveRoom_limlt").val();
					//获取当前每页大小
					var recodeLimit =  tableInsLiveRoom.config.limit;
					//设置零时保留的值
					$("#liveRoom_limlt").val(recodeLimit);
					//判断是否改变了每页大小数
					if (last_value != recodeLimit){
						// 刷新
						table.reload("liveRoom_table",{
							url:request("/console/liveRoomList"),
							page: {
								curr: 1 //重新从第 1 页开始
							}
						})
					}

					var pageIndex = tableInsLiveRoom.config.page.curr;//获取当前页码
					var resCount = res.count;// 获取table总条数
					currentCount = resCount;
					currentPageIndex = pageIndex;


					$("#liveRoomList").show();
					$("#liveRoomByUser").hide();
					$(".searchLive").show();
					$(".searchLive_").hide();
					$(".roomNameDiv").show();
					$(".createUserIdDiv").hide();
					$(".visitPathDiv").hide();
				}
			});
		}
	});


    //列表操作
    table.on('tool(liveRoom_table)', function(obj){
         var layEvent = obj.event,
            data = obj.data;

         if(layEvent === 'member'){ //成员管理
        	var tableIns1 = table.render({
			  elem: '#liveRoomMember_table'
			  ,url:request("/console/liveRoomUserManager")+"&roomId="+data.roomId
			  ,id: 'liveRoomMember_table'
			  ,toolbar: '#toolbar'
			  ,page: true
			  ,curr: 0
			  ,limit:Common.limit
			  ,limits:Common.limits
			  ,groups: 7
			  ,cols: [[ //表头
				   {field: 'userId', title: '用户Id', width:220}
				  ,{field: 'nickName', title: '昵称', width:200}
				  ,{field: 'state',title:"状态", width:150,templet: function(d){
						if(d.state==1){
							return  "禁言";
						}else{
							return "正常";
						}
					}}
				  ,{field: 'createTime', title: '加入时间', width:400,templet: function(d){
						return UI.getLocalTime(d.createTime);
				  }}
				  ,{fixed: 'right', width: 240,title:"操作", align:'left', toolbar: '#liveRoomMemberListBar'}
				]]
				,done:function(res, curr, count){
					checkRequst(res);
					$("#liveRoomList").hide();
					$("#liveRoomUser").show();
					$(".visitPathDiv").hide();
					$(".searchLive").hide();
					$(".searchLive_").hide();
					$("#save_roomId").val(Common.filterHtmlData(data.roomId));
				}
			});
        }else if(layEvent === 'chatMessage'){// 聊天记录
        	var tableIns1 = table.render({
			      elem: '#liveRoomMsg_table'
			      ,url:request("/console/roomMsgDetail")+"&room_jid_id="+data.jid
			      ,id: 'liveRoomMsg_table'
				  ,toolbar: '#toolbar'
			      ,page: true
			      ,curr: 0
                  ,limit:Common.limit
                  ,limits:Common.limits
			      ,groups: 7
			      ,cols: [[ //表头
			           {field: 'room_jid', title: '房间Id', width:220}
			          ,{field: 'sender', title: '发送者Id', width:98}
			          ,{field: 'fromUserName', title: '发送者', width:220}
			          ,{field: 'ts', title: '时间', width:400,templet: function(d){
			          		return UI.getLocalTime(d.timeSend/1000);
			          }}
			          ,{field: 'content',title:'内容',width:220,templet : function (d) {
							if(!Common.isNil(d.content)){
								if(1 == d.isEncrypt && localStorage.getItem("role")==6){
									var desContent = Common.decryptMsg(d.content,d.messageId,d.timeSend);
									if(desContent.search("https") != -1||desContent.search("http")!=-1){
										var link = "<a target='_blank' href=\""+desContent+"\">"+desContent+"</a>";
										return link;
									}else{
										return desContent;
									}
								}else{
									var text = (Object.prototype.toString.call(d.content) === '[object Object]' ? JSON.stringify(d.content) : d.content)
									try {
										if(text.search("https") != -1||text.search("http")!=-1){
											var link = "<a target='_blank' href=\""+text+"\">"+text+"</a>";
											return link;
										}else{
											return text;
										}
									}catch (e) {
										return text;
									}
								}
							}else {
								return "";
							}
						}}]]
					,done:function(res, curr, count){
						checkRequst(res);
						$("#liveRoomList").hide();
						$(".visitPathDiv").hide();
						$(".searchLive").hide();
					    $(".searchLive_").show();
						$("#liveRoomMsg").show();
					}
			    });
        }else if(layEvent === 'modifyRtmpUrl'){ //修改推流地址

            //prompt层
            layer.prompt({title: '请输入新的rtmp推流地址，并确认', formType: 0}, function(text, index){
              layer.close(index);

              Common.invoke({
                    url:request('/console/updateLiveRoomRtmpUrl'),
                    data:{
                        liveRoomId:data.roomId,
                        newRtmpUrl:text
                    },
                    successMsg : "更新直播间rtmp直播推流地址成功",
                    errorMsg :  "更新直播间rtmp直播推流地址失败，请稍后重试",
                    success : function(result) {
                        layui.table.reload("liveRoom_table")
                    },
                    error : function(result) {
                    }
              })


            });

        }
      });


    //列表操作
    table.on('tool(liveRoomMember_table)', function(obj){
         var layEvent = obj.event,
            data = obj.data;
         if(layEvent === 'remove'){ // 剔除
         	Live.deleteRoomUser(data.userId,$("#save_roomId").val(),obj);

         } else if(layEvent === 'shutup'){// 禁言
         	Live.shutup(data.userId,$("#save_roomId").val(),1);
         }else if(layEvent === 'cancelShutup'){
             Live.shutup(data.userId,$("#save_roomId").val(),0);
         }
    })

    //搜索
    $(".search_live").on("click",function(){
        // 关闭超出宽度的弹窗
        $(".layui-layer-content").remove();
		table.reload("liveRoom_table",{
			url:request("/console/liveRoomList"),
			where: {
				userId : thisUserId,
				name : Common.getValueForElement("#roomName")
			},
			page: {
				curr: 1 //重新从第 1 页开始
			}
		});
    });

	//搜索
	$(".search_live_").on("click",function(){
		// 关闭超出宽度的弹窗
		$(".layui-layer-content").remove();

		table.reload("liveRoomByUser_table",{
			url:request("/console/find/liveroom"),
			where: {
				userId : Common.getValueForElement("#createUserId"),
			},
			page: {
				curr: 1 //重新从第 1 页开始
			}
		});
	});

});
var Live={

	// 新增直播间
	addLiveRoom:function(){
		$(".liveRoom_div").hide();
		$(".liveRoom_div").hide();
		$("#addLiveRoom").show();
		$("#liveRoomName").val("");
        $(".visitPathDiv").hide();
	},
	commit_addLiveRoom:function(){
		if($("#liveRoomName").val()==""){
			layer.alert("直播间名称不能为空");
			return ;
		}else if($("#liveRoomNotic").val()==""){
			layer.alert("直播间说明不能为空");
			return ;
		}
		Common.invoke({
			url:request('/console/saveNewLiveRoom'),
			data:{
				userId:thisUserId,
				name:$("#liveRoomName").val(),
				notice:$("#liveRoomNotic").val()
			},
			success:function(result){
				if(result.resultCode == 1){
					layer.alert("添加直播间成功");
					$("#addLiveRoom").hide();
					$(".liveRoom_div").show();
                    /*layui.table.reload("liveRoom_table",{
                        page: {
                            curr: 1 //重新从第 1 页开始
                        },
                        where: {
                        }
                    })*/
					Common.tableReload(currentCount,currentPageIndex,1,"liveRoom_table");
				}else if(result.resultCode == 0){
					layer.alert(result.resultMsg);
				}
			},

		})
	},


	// 锁定解锁直播间
	deleteLiveRoom:function(id,currentState){
        var confMsg,successMsg="";
        (currentState == 1 ? confMsg = '确定封锁该直播间？':confMsg = '确定解封该直播间？');
        (currentState == 1 ? successMsg = "封锁成功":successMsg ="解封成功");
		layer.confirm(confMsg,{icon:3, title:'提示信息',skin : "layui-ext-motif"},function(index){
			Common.invoke({
	            url:request('/console/operationLiveRoom'),
				data:{
					liveRoomId:id,
					currentState:currentState
				},
				successMsg : successMsg,
				errorMsg :  "加载数据失败，请稍后重试",
				success : function(result) {
				},
				error : function(result) {
				}

		})
		})
		
	},

	// 踢出直播间成员
	deleteRoomUser:function(userId,roomId,obj){
		layer.confirm('确定踢出该成员？',{icon:3, title:'提示信息',skin : "layui-ext-motif"},function(index){
			Common.invoke({
				url:request('/console/deleteRoomUser'),
				data:{
					userId:userId,
					liveRoomId:roomId
				},
				success:function(result){
					if(result.resultCode==1){
						layer.alert("踢出成功");
                        obj.del();
                        layui.table.reload("liveRoomMember_table")
					}
				}
			})

		});
		
	},
	// 用户禁言
	shutup:function(userId,roomId,state){
		var confMsg,successMsg="";
		(state == 0 ? confMsg = '确定取消禁言该成员？':confMsg = '确定禁言该成员？');
		(state == 0 ? successMsg = "取消禁言成功":successMsg ="禁言成功");
		layer.confirm(confMsg,{icon:3, title:'提示信息',skin : "layui-ext-motif"},function(index){

            Common.invoke({
                url : request('/console/shutup'),
                data : {
                    'userId':userId,
                    'state':state,
                    'roomId':roomId
                },
                successMsg : successMsg,
                errorMsg :  "加载数据失败，请稍后重试",
                success : function(result) {
                    layui.table.reload("liveRoomMember_table",{

                    })
                },
                error : function(result) {
                }
            });
		})
	},
	btn_back:function(){
		$(".liveRoom_div").show();
		$("#liveRoomList").hide();
		$("#addLiveRoom").hide();
		$("#liveRoomMsg").hide();
		$("#liveRoomUser").hide();
		$("#liveRoomGiftWater").hide();
		$(".visitPathDiv").show();
		$("#liveRoomByUser").show();
		$(".searchLive").hide();
		$(".searchLive_").show();
	},
	backMsg:function(){
		$("#liveRoomMsg").hide();
		$("#liveRoomList").show();
	},
	backUser:function(){
		$("#liveRoomUser").hide();
		$("#liveRoomList").show();
	},

}

$(function () {
	//调用父级页面的Js函数
	window.parent.getJointVisitPath();
})